import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { join } from 'path';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ResponseInterceptor } from './common/response';
// import { HttpFilter } from './common/filter/http-exception.filter';
import { ValidationPipe, VERSION_NEUTRAL, VersioningType } from '@nestjs/common';
import session from 'express-session';
import cors from 'cors';
import { Request, Response, NextFunction } from 'express';
// import { GuardGuard } from './guard/guard.guard';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AllExceptionFilter } from './common/filter/all-exception.filter';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { ConfigService } from '@nestjs/config';


//全局中间件，只能是函数，不能是类
function MiddlewareAll(req: Request, res: Response, next: NextFunction) {
  const whiteList = ['/hello']
  console.log(req.originalUrl, req.path)
  if (whiteList.includes(req.path)) {
    next()
  } else {
    res.send({ message: '没有权限' })
  }
}

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: ['error', 'log', 'warn'], // 关闭nestjs的日志
  });
  app.use(cors())
  app.use(session({ secret: "XiaoMan", name: "xm.session", rolling: true, cookie: { maxAge: 10000 } }))


  const config = new ConfigService()
  const version = config.get('VERSION')
  const prefix = config.get('PREFIX', '/api')

  // 设置接口前缀
  app.setGlobalPrefix(prefix);
  // 设置接口版本
  app.enableVersioning({
    type: VersioningType.URI,
    defaultVersion: typeof version == 'undefined' ? VERSION_NEUTRAL : [version]
  });
  // 设置静态资源访问useStaticAssets prefix 是虚拟前缀
  app.useStaticAssets(join(__dirname, 'images'), {
    prefix: '/wenjian'
  });
  // 注册响应连拦截器
  // app.useGlobalInterceptors(new ResponseInterceptor())
  // 注册异常过滤器
  const httpAdapterHost = app.get(HttpAdapterHost); 
  app.useGlobalFilters(new AllExceptionFilter(httpAdapterHost))
  // 注册全局DTO验证管道
  app.useGlobalPipes(new ValidationPipe({
    // 去除类上不存在的字段数
    whitelist: true,
    // 自动转换请求对象到DTO实例
    transform: true,
    transformOptions: {
      // 允许类转换器隐式转换字段类型，如将字符串转换为数字等
      enableImplicitConversion: true,
    }
  }))
  // 自动配置winston的logger
  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER))
  // 注册全局守卫
  // app.useGlobalGuards(new GuardGuard())
  
  // 启用关闭应用监听
  app.enableShutdownHooks()

  // swagger文档设置
  const options = new DocumentBuilder().setTitle('小满接口文档').setDescription('描述，。。。').setVersion('1').build()
  const document = SwaggerModule.createDocument(app,options)
  SwaggerModule.setup('/api-docs',app,document)


  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
